global root_dir = "`1'"
include "$root_dir/code/config/config.do"

cap noi log using ${log_dir}/Table_A4a_top_innovators.log, replace name(tabl)

capture noi {

texdoc init ${tab_dir}/appendix/Table_A4a_top_innovators.tex, replace
texdoc stlog, nolog

use ${dataset_dir}/patstat_orbis/BvD_largest_group_remap.dta, clear
keep group_old group_new
duplicates drop
tempfile remap
save `remap'

** Automation patent counts in the 1997-2011 sample period for the regression firms.
use BvD year lse_id ${depvar}_${ttt} using ${final_dir}/regression_dataset${weight_window}${tf}.dta, clear
mmerge BvD using ${final_dir}/bvd_list_regfirms_${depvar}.dta, unmatched(master)
keep if _m == 3
drop _m
bys lse_id : egen _total_${depvar}_${ttt}_1995 = sum(${depvar}_${ttt}) if year>=1995+2 & year <= 2009+2
bys lse_id : egen total_${depvar}_${ttt}_1995 = max(_total_${depvar}_${ttt}_1995)
drop _total_${depvar}_${ttt}_1995
keep BvD total
duplicates drop
mmerge BvD using ${final_dir}/BvD_industry.dta, unmatched(master)
gsort -total
keep if _n <= 30
mmerge BvD using `remap', umatch(group_old) ukeep(group_new) unmatched(master)
drop BvD
ren group_new group
tempfile mfirm_pats
save `mfirm_pats'

drop _m
gsort -total



forvalues i = 1/10 { 
    sleep 4000
    texdoc local `i'_a95 : display %9.0f total_auto95_bia_1995[`i']
}

*hardcoding the top 10 companies- we used an orbis file originally to get the top 10 companies names but cannot include that
* check the BvD numbers in the code at this stage and compare it against an appropriate Orbis file if you would like to check
sleep 4000
texdoc local 1_company = "Siemens Aktiengesellschaft"
sleep 4000
texdoc local 2_company = "Honda Motor Co., Ltd."
sleep 4000
texdoc local 3_company = "Fanuc Co."
sleep 4000
texdoc local 4_company = "Samsung Electronics Co., Ltd."
sleep 4000
texdoc local 5_company = "Mitsubishi Electric Co."
sleep 4000
texdoc local 6_company = "Robert Bosch Gmbh"
sleep 4000
texdoc local 7_company = "Tokyo Electron Limited"
sleep 4000
texdoc local 8_company = "Murata Machinery, Ltd."
sleep 4000
texdoc local 9_company = "Kabushiki Kaisha Toshiba"
sleep 4000
texdoc local 10_company = "Panasonic I.P.M Co., Ltd."
sleep 4000

* output table (via texdoc)
texdoc local notes "This table reports the 10 firms with the highest number of biadic auto95 patents in our baseline sample."
texdoc stlog close
qui include ${code_dir}/config/texdoctools.do
tex `texpreamble'
/*tex
\begin{tabular}{@{}lr@{}}
\toprule
Company& \makecell[r]{Auto95's \\ in 1997-2011} \\
\midrule
`1_company' & `1_a95' \\
`2_company' & `2_a95' \\
`3_company' & `3_a95' \\
`4_company' & `4_a95' \\
`5_company' & `5_a95' \\
`6_company' & `6_a95' \\
`7_company' & `7_a95' \\
`8_company' & `8_a95' \\
`9_company' & `9_a95' \\
`10_company' & `10_a95' \\
\bottomrule
\end{tabular}
tex*/
tex `texpostamble'
texdoc close
}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close tabl
